package parser

import (
	"gitee.com/shu2015626/go_start_imooc/chapter13-crawler/concurrency_crawler/engine"
	"gitee.com/shu2015626/go_start_imooc/chapter13-crawler/concurrency_crawler/model"
	"regexp"
	"strconv"
)

var ageRe = regexp.MustCompile(`<div[^>]+>([\d]+)岁</div>`)
var workPlaceRe = regexp.MustCompile(`<div[^>]+>工作地:([^<]+)</div>`)
var incomeRe = regexp.MustCompile(`<div[^>]+>月收入:([^<]+)</div>`)

func ParseProfile(contents []byte, name string) engine.ParseResult {
	profile := model.Profile{}

	profile.Name = name

	age, err := strconv.Atoi(extractString(contents, ageRe))
	if err == nil {
		//user age is age
		profile.Age = age
	}

	profile.WorkPlace = extractString(contents, workPlaceRe)

	profile.Income = extractString(contents, incomeRe)

	result := engine.ParseResult{
		Items: []interface{}{profile},
	}

	return result

}

func extractString(contents []byte, re *regexp.Regexp) string {
	match := re.FindSubmatch(contents)

	if len(match) >= 2 {
		return string(match[1])
	} else {
		return ""
	}
}
